package com.ds.yuntukubackend.aop;

import com.ds.yuntukubackend.annotation.AuthCheck;
import com.ds.yuntukubackend.exception.ErrorCode;
import com.ds.yuntukubackend.exception.ThrowUtils;
import com.ds.yuntukubackend.model.entity.User;
import com.ds.yuntukubackend.model.enums.UserRoleEnum;
import com.ds.yuntukubackend.service.UserService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint , AuthCheck authCheck) throws Throwable {
        //1.该方法应需要的权限
        String mustRole = authCheck.mustRole();
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //如果不需要权限，直接放行
        if(mustRoleEnum == null){
            return joinPoint.proceed();
        }
        //2.获取当前用户登录信息
        //requestContextHolder：请求上下文持有者, 用于在线程范围内存储和访问请求相关的属性。
        //currentRequestAttributes(): 当前请求属性,方法返回当前线程中的RequestAttributes 对象，该对象包含了当前请求的相关信息。
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        User loginUser = userService.getLoginUser(request);
        //3.获取该用户拥有的权限
        UserRoleEnum userHasRole = UserRoleEnum.getEnumByValue(loginUser.getRole());
        //如果没有权限，抛出无权限异常
        ThrowUtils.throwIf(userHasRole == null, ErrorCode.NO_AUTH_ERROR);
        //如果要求管理员权限，而用户没有管理员权限，拒绝
        ThrowUtils.throwIf(UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userHasRole),
                ErrorCode.NO_AUTH_ERROR);

        //4.放行
        return joinPoint.proceed();
    }
}
